﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Runtime.InteropServices.Automation;
using Microsoft.LightSwitch.Threading;
using System.Windows.Browser;
using System.Reflection;
namespace LightSwitchApplication
{
    public partial class Home
    {
        public static void NavigateUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return;
            var uri = new Uri(url, UriKind.RelativeOrAbsolute);

            Dispatchers.Main.BeginInvoke(() =>
            {
                try
                {
                    if (AutomationFactory.IsAvailable)
                    {
                        var shell = AutomationFactory.CreateObject("Shell.Application");
                        shell.ShellExecute(uri.ToString());

                    }
                    else if (!System.Windows.Application.Current.IsRunningOutOfBrowser)
                    {
                        HtmlPage.Window.Navigate(uri, "_blank");
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }

                }
                catch
                {
                    //handle the exception however you want  
                }
            });
            // Set handled to 'true' to stop further processing.  
            //handled = true;
        }


        partial void CloseAllWindows_Execute()
        {
            // Write your code here.
            for (int index = Application.ActiveScreens.Count - 1; index >= 0; index--)
            {
                if (Application.ActiveScreens[index].GetName() != "Home")
                    Application.ActiveScreens[index].Close(false);
            }
        }

        partial void ShowHelp_Execute()
        {
            NavigateUrl("http://project01.codeplex.com/workitem/list/basic");
        }

        partial void Home_InitializeDataWorkspace(List<IDataService> saveChangesTo)
        {
            this.CurrentDate = DateTime.Today;
            string userName = this.Application.User.FullName;
            LblGreeting = "Здравствуйте, " + userName;

            //IEnumerable<Microsoft.LightSwitch.Security.UserRegistration> userRegistrations = this.DataWorkspace.SecurityData.UserRegistrations.Where(r => r.UserName == this.Application.User.Name).Select(r => r.FullName);
            //var users = from role in userRegistrations
            //            select role.RoleAssignments.Select(r => r.User);
            //List<UserRegistration> userRegistrations = null;
            //foreach (IEnumerable<UserRegistration> registrations in users)
            //    if (userRegistrations == null)
            //        userRegistrations = registrations.ToList();
            //    else
            //        userRegistrations.AddRange(userRegistrations);
            //userRegistrations = userRegistrations.Distinct().ToList();

            //query = from approver in query
            //        join userRegistration in userRegistrations on approver.UserId equals userRegistration.UserName
            //        select approver;

            //Permission permission = this.DataWorkspace.SecurityData.Permissions.Where(p => p.Name.Equals(Permission, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();

            //LblGreeting += "\nВаши роли в программе: ";
            //foreach (var item in this.DataWorkspace.SecurityData.Permissions)//.Where(p => this.Application.User.HasPermission(p.PermissionId))
            //{
            //    if (this.Application.User.HasPermission(((Microsoft.LightSwitch.Security.Permission)item).Id))
            //        LblVersion += " - " + item.ToString() + "\n";
            //}
            try
            {
                foreach (aspnet_Profile item in this.DataWorkspace.SalesDepData.aspnet_Profiles)
                {
                    if (item.PropertyValuesString == userName && item.aspnet_User != null)
                    {
                        foreach (aspnet_UsersInRole role in item.aspnet_User.aspnet_UsersInRoles)
                        {
                            LblVersion += " - " + role.aspnet_Role.RoleName + "\n";
                        }
                    }
                }
            }
            catch (Exception)
            {
                
            }

            LblVersion = GetVersionNr();
            //this.DataWorkspace.SecurityData.ChangePassword(this.Application.User.Name, oldPassword, newPassword)
        }

        private string GetVersionNr()
        {
            var name = new AssemblyName(System.Reflection.Assembly.GetExecutingAssembly().FullName);
            return name.Version.ToString();
        }

        partial void CreateNewVisit_Execute()
        {
            this.Application.ShowCreateNewVisit(null);
        }

        partial void CreateNewOrder_Execute()
        {
            this.Application.ShowCreateNewSalesOrder(null);
        }

        partial void NavigateToDiscussion_Execute()
        {
            NavigateUrl("http://project01.codeplex.com/discussions");
        }

        partial void NavigateToDocumentation_Execute()
        {
            NavigateUrl("http://project01.codeplex.com/documentation");
        }

        partial void Login_Execute()
        {
            Dispatchers.Main.Invoke(() =>
            {
                HtmlPage.Window.Navigate(new Uri("Relogin.aspx", UriKind.Relative));
            });
        }

        partial void CreateNewShop_Execute()
        {
            this.Application.ShowCreateNewShop(0,0);
        }

        partial void CreateNewShop_CanExecute(ref bool result)
        {
            result = (this.Application.User.HasPermission(Permissions.CanEditShop)
                    || this.Application.User.HasPermission(Permissions.CanManageMyShop)
                );
        }

        partial void CreateNewOrder_CanExecute(ref bool result)
        {
            result = (this.Application.User.HasPermission(Permissions.CanEditSalesOrder)
                    || this.Application.User.HasPermission(Permissions.CanManageMySalesOrder)
                );
        }

        partial void CreateNewCustomer_Execute()
        {
            this.Application.ShowCreateNewCustomer();
        }

        partial void CreateNewCustomer_CanExecute(ref bool result)
        {
            result = this.Application.User.HasPermission(Permissions.CanEditCustomer);
        }

        partial void CreateNewVisit_CanExecute(ref bool result)
        {
            result = (this.Application.User.HasPermission(Permissions.CanEditVisit)
                    || this.Application.User.HasPermission(Permissions.CanManageMyVisit)
                );
        }

    }
}
